package com.crk.javaTools;

import com.crk.javaTools.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * Description:
 * 常见的文件相关操作
 * @author: chengrongkai
 * Date: 2020-07-09
 * Time: 14:34
 */
@RestController
@RequestMapping("file")
public class FileTools {
    @Autowired
    HttpServletRequest request;


    /**
     * 上传文件-存储在服务器
     * @param file 文件
     * @return
     */
    @PostMapping("/upload")
    public ResponseResult upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseResult.fail("上传失败,上传文件不允许为空");
        }

        String fileName = file.getOriginalFilename();
        String filePath = getUploadPath();
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            System.out.println("上传成功");
            return ResponseResult.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.fail("上传失败");
        }

    }

    public static String getUploadPath(){
        try {
            File directory = new File("src/main/resources");
            String courseFile = directory.getCanonicalPath();
            String filePath = courseFile+"/static/upload/";
            return filePath;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 多文件上传-存储在服务器
     * @param files
     * @return
     */
    @PostMapping("/uploadMulti")
    public ResponseResult uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) {
        boolean result = true;
        for (MultipartFile file : files) {
            ResponseResult responseResult = upload(file);
            if (!ResponseResult.isSuccess(responseResult)){
                result = false;
                break;
            }
        }
        if (result){
            return ResponseResult.success();
        }else{
            return ResponseResult.fail("上传失败");
        }
    }

    /**
     * 一般的文件通过流输出-直接下载文件
     * @param fileName 文件名
     * @param response 响应
     * @throws Exception
     */
    @GetMapping("getFile")
    public void getFile(@RequestParam("fileName") String fileName,HttpServletResponse response){
        String filePath = getUploadPath();
        filePath = filePath+fileName;
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        try {
            File file = new File(filePath);
            fileInputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();

            response.setContentType("application/octet-stream");
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Content-disposition",
                    "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] buf = new byte[1024];
            int length = 0;
            //循环读取文件内容，输入流中将最多buf.length个字节的数据读入一个buf数组中,返回类型是读取到的字节数。
            //当文件读取到结尾时返回 -1,循环结束。
            while((length = fileInputStream.read(buf)) != -1){
                outputStream.write(buf);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (null != fileInputStream){
                    fileInputStream.close();
                }
                if (null != outputStream){
                    outputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

    }


    /**
     * 图片在线预览
     * @param fileName 文件名
     * @param response 响应
     * @throws Exception
     */
    @GetMapping("getImage")
    public void getFileShow(@RequestParam("fileName") String fileName,HttpServletResponse response){
        String filePath = request.getServletContext().getRealPath("/")+"upload/";
        filePath = filePath+fileName;
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        try {
            File file = new File(filePath);
            fileInputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();

            byte[] buf = new byte[1024];
            int length = 0;
            //循环读取文件内容，输入流中将最多buf.length个字节的数据读入一个buf数组中,返回类型是读取到的字节数。
            //当文件读取到结尾时返回 -1,循环结束。
            while((length = fileInputStream.read(buf)) != -1){
                outputStream.write(buf);
            }
            response.setContentType("image/jpeg");
            response.setHeader("Content-disposition",
                    "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (null != fileInputStream){
                    fileInputStream.close();
                }
                if (null != outputStream){
                    outputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

    }

    /**
     * 图片在线预览
     * @param fileName 文件名
     * @param response 响应
     * @throws Exception
     */
    @GetMapping("getPdf")
    public void getPDFShow(@RequestParam("fileName") String fileName,HttpServletResponse response){
        String filePath = request.getServletContext().getRealPath("/")+"upload/";
        filePath = filePath+fileName;
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        try {
            File file = new File(filePath);
            fileInputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();

            byte[] buf = new byte[1024];
            int length = 0;
            //循环读取文件内容，输入流中将最多buf.length个字节的数据读入一个buf数组中,返回类型是读取到的字节数。
            //当文件读取到结尾时返回 -1,循环结束。
            while((length = fileInputStream.read(buf)) != -1){
                outputStream.write(buf);
            }
            response.setContentType("application/pdf");
            response.setHeader("Content-disposition",
                    "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (null != fileInputStream){
                    fileInputStream.close();
                }
                if (null != outputStream){
                    outputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

    }


}
